<template>
  <view class="content">
    <view class="content-header">
      <checkbox class="select-all" :checked="allSelected" @click="toggleAllSelection">全选</checkbox>
      <text class="clear-cart-text" @click="clearCart">清空购物车</text>
    </view>
    <hr style="border-color: #ccc; opacity: 0.5;">
    <view class="cart-empty" v-if="cartList.length === 0">
      <text class="cart-empty-text">购物车空空如也</text>
    </view>
    <view class="cart-list" v-for="(list, shopId) in shopCartList" :key="shopId" v-if="list.items.length > 0">
      <view class="cart-list-title">{{ getShopName(shopId) }}</view>
      <view class="cart-list-item" v-for="(item, index) in list.items" :key="index" :class="{ 'cart-list-item-selected': item.selected }">
        <view class="cart-list-item-left">
          <checkbox :value="item.id" :checked="item.selected" @click="toggleItemSelection(item)" class="cart-item-checkbox"></checkbox>
          <image :src="item.imgUrl" class="cart-list-item-img"></image>
        </view>
        <view class="cart-list-item-right">
          <text class="cart-list-item-name">{{ item.name }}</text>
          <text class="cart-list-item-price">￥{{ item.price }}</text>
          <text class="cart-list-item-count">数量:{{ item.count }}</text>
          <text class="remove-cart-text" @click="removeItem(item)">移除购物车</text>
        </view>
      </view>
    </view>
    <view class="cart-list-item-total">
      <text class="total-price">总价:￥{{ selectedTotalPrice }}</text>
      <button class="checkout-button primary" @click="gotoConfirmOrder" v-if="this.cartList.length > 0">结算</button>
    </view>
  </view>
</template>

<style scoped>
  /* 全局样式 */
  body {
    font-family: 'Open Sans', sans-serif;
    margin: 0;
    padding: 0;
    background-color: #eaf2f8;
  }

 .content {
    width: 100%;
    margin: 0 auto;
    height: auto;
    background-color: white;
    padding: 30px;
    box-sizing: border-box;
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    animation: fadeInUp 0.5s ease;
  }

  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  /* 头部样式 */
 .content-header {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
  }

  /* 全选复选框样式 */
 .select-all {
    margin-top: 0;
    font-size: 18px;
    color: #444;
  }

  /* 清空购物车文字样式 */
 .clear-cart-text {
    font-size: 12px;
    color: #ff5555;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s ease;
  }

 .clear-cart-text:hover {
    color: #ff3333;
  }

  /* 移除购物车文字样式 */
 .remove-cart-text {
    font-size: 12px;
    color: #ff5555;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s ease;
  }

 .remove-cart-text:hover {
    color: #ff3333;
  }

 .button,
 .checkout-button {
    float: none;
    width: 140px;
    height: 40px;
    margin-top: 0;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

 .primary {
    background-color: #00a2ff;
    color: white;
  }

 .primary:hover {
    background-color: #0087e6;
  }

  /* 购物车为空提示样式 */
 .cart-empty {
    text-align: center;
    margin-top: 20px;
    color: #666;
    font-size: 18px;
  }

  /* 购物车列表标题样式 */
 .cart-list-title {
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 20px;
    font-weight: bold;
    color: #444;
    border-bottom: 1px solid #d3e1ec;
    margin-bottom: 15px;
  }

  /* 购物车列表项样式 */
 .cart-list-item {
    width: 100%;
    height: 130px;
    display: flex;
    align-items: center;
    background-color: #f5f9fd;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    margin-bottom: 15px;
    padding: 15px;
    box-sizing: border-box;
    transition: box-shadow 0.3s ease, transform 0.3s ease;
  }

 .cart-list-item-selected {
    background-color: #e0f2ff;
  }

 .cart-list-item:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  /* 购物车列表项左侧样式 */
 .cart-list-item-left {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }

  /* 购物车列表项图片样式 */
 .cart-list-item-img {
    width: 90px;
    height: 90px;
    object-fit: cover;
    border-radius: 6px;
  }

  /* 购物车列表项右侧样式 */
 .cart-list-item-right {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  /* 购物车列表项名称样式 */
 .cart-list-item-name {
    font-size: 18px;
    color: #333;
    margin-bottom: 8px;
  }

  /* 购物车列表项价格样式 */
 .cart-list-item-price {
    font-size: 16px;
    color: #f60;
    margin-bottom: 8px;
  }

  /* 购物车列表项数量样式 */
 .cart-list-item-count {
    font-size: 16px;
    color: #666;
  }

  /* 购物车总价和结算按钮样式 */
 .cart-list-item-total {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 25px;
    font-size: 18px;
    color: #444;
  }

 .total-price {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }

  /* 购物车项复选框样式 */
 .cart-item-checkbox {
    margin-right: 15px;
  }
</style>

<script>
<<<<<<< HEAD
import config from '../../config';
=======
import axios from 'axios';
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751

export default {
  data() {
    return {
      cartList: [],
      shopList: [],
      shopCartList: {},
    };
  },
  computed: {
    allSelected() {
      return this.cartList.every(item => item.selected);
    },
    selectedTotalPrice() {
      let total = 0;
      this.cartList.forEach(element => {
        if (element.selected) {
          total += element.price * element.count;
        }
      });
      return total.toFixed(2);
    }
  },
  methods: {
    removeItem(item) {
      console.log(item.id);
<<<<<<< HEAD
      uni.request({
        url: config.URL + `/cart/${item.id}`,
        method: 'DELETE',
        success: (res) => {
          console.log("移除", item);
          // 从本地数组移除该项
          this.cartList = this.cartList.filter(cartItem => cartItem.uniqueId!== item);
          window.location.reload();
          // 重新分类以更新 shopCartList
          this.classifyCartItems();
          uni.showToast({
            title: '已移除购物车',
            icon: 'success',
          });
        },
        fail: (error) => {
          console.error('移除购物车项时出错', error);
        }
=======
      axios.delete(`https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart/${item.id}`).then(res => {
        console.log("移除", item);
        // 从本地数组移除该项
        this.cartList = this.cartList.filter(cartItem => cartItem.uniqueId!== item);
        window.location.reload();
        // 重新分类以更新 shopCartList
        this.classifyCartItems();
        uni.showToast({
          title: '已移除购物车',
          icon: 'success',
        });
      }).catch(error => {
        console.error('移除购物车项时出错', error);
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
      });
    },
    getShopName(shopId) {
      const shop = this.shopList.find(shop => shop._id === shopId);
      return shop? shop.name : '未知超市';
    },
    classifyCartItems() {
      this.shopCartList = {};
      this.cartList.forEach(element => {
        const shopId = parseInt(element.shopId);
        if (!this.shopCartList[shopId]) {
          this.shopCartList[shopId] = {
            shopId: shopId,
            items: []
          };
        }
        this.shopCartList[shopId].items.push(element);
      });
    },
    toggleAllSelection() {
      const allSelected =!this.allSelected;
      this.cartList.forEach(item => {
        item.selected = allSelected;
      });
      this.classifyCartItems();
    },
    toggleItemSelection(item) {
      item.selected =!item.selected;
      this.classifyCartItems();
    },
    clearCart() {
<<<<<<< HEAD
      uni.request({
        url: config.URL + "/cart",
        method: 'GET',
        data: {
          userId: uni.getStorageSync('ID')
        },
        success: (res) => {
          const items = res.data;
          const deletePromises = items.map(item => {
            return new Promise((resolve, reject) => {
              uni.request({
                url: config.URL + `/cart/${item.id}`,
                method: 'DELETE',
                success: () => {
=======
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", {
        params: {
          userId: uni.getStorageSync('ID')
        }
      })
       .then(res => {
          const items = res.data;
          const deletePromises = items.map(item => {
            return axios.delete(`https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart/${item.id}`)
              .then(() => {
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
                  console.log(`ID 为 ${item.id} 的记录已删除`);
                  uni.showToast({
                    title: '清除成功',
                  });
<<<<<<< HEAD
                  resolve();
                },
                fail: (error) => {
                  console.error(`删除 ID 为 ${item.id} 的记录时出错`, error);
                  reject(error);
                }
              });
            });
=======
                })
              .catch(error => {
                  console.error(`删除 ID 为 ${item.id} 的记录时出错`, error);
                });
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
          });

          Promise.all(deletePromises).then(() => {
            this.cartList = [];
            this.classifyCartItems();
            uni.showToast({
              title: '购物车已清空',
            });
          })
          .catch(error => {
            console.error('删除操作出错', error);
          });
<<<<<<< HEAD
        },
        fail: (error) => {
          console.error('获取数据时出错', error);
        }
      });
    },
    onShow() {
      uni.request({
        url: config.URL + "/shop",
        method: 'GET',
        success: (res) => {
          this.shopList = res.data;
          console.log(this.shopList);
        },
        fail: (error) => {
          console.error('获取店铺数据时出错', error);
        }
      });
      uni.request({
        url: config.URL + "/cart",
        method: 'GET',
        data: {
          userId: uni.getStorageSync('ID')
        },
        success: (res) => {
          this.cartList = res.data.map(item => ({...item, selected: true }));
          console.log(this.cartList);
          this.classifyCartItems();
        },
        fail: (error) => {
          console.error('获取购物车数据时出错', error);
        }
      });
    },
    gotoConfirmOrder() {
     const selectedItems = this.cartList.map(item => ({...item, selected: true }));
=======
        })
       .catch(error => {
          console.error('获取数据时出错', error);
        });
    },
    onShow() {
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/shop").then((res) => {
        this.shopList = res.data;
        console.log(this.shopList);
      });
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", {
        params: {
          userId: uni.getStorageSync('ID')
        }
      }).then((res) => {
        this.cartList = res.data.map(item => ({...item, selected: true }));
        console.log(this.cartList);
        this.classifyCartItems();
      });
    },
    gotoConfirmOrder() {
      const selectedItems = this.cartList.filter(item => item.selected);
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
      if (selectedItems.length === 0) {
        uni.showToast({ title: '请选择要结算的商品', icon: 'none' });
        return;
      }
      uni.navigateTo({
        url: `/pages/confirmorder/index?selectedItems=${encodeURIComponent(JSON.stringify(selectedItems))}`
      });
    }
  }
<<<<<<< HEAD
};    
=======
};
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
</script>